/*
 * BanBu_ThemeViewController
 * @description 本文件提供主题更换界面的ViewController
 * @package
 * @author 		***
 * @copyright
 * @version 		1.0
 * @description 本文件提供主题更换界面的ViewController
 */

#import "BanBu_ThemeViewController.h"
#import "BanBu_ThemeManager.h"
#import "AppCommunicationManager.h"
#import "AppDataManager.h"
#import "BanBuAPIs.h"
#import "BanBu_NavButton.h"
#import "BanBu_ImageView.h"

#import "ETActivityIndicatorView.h"
@interface BanBu_ThemeViewController ()

@end
#define  cellHeight 124
@implementation BanBu_ThemeViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
    }
    return self;
}
-(void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"downLoadThemeComplete" object:nil];
    [_themeTable release],_themeTable = nil;
    [themeArr release],themeArr = nil;
    [super dealloc];
    //    [selectedImageView release],selectedImageView = nil;
}
-(void)popself
{
    [self.navigationController popViewControllerAnimated:YES];
}
-(void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:YES];
    [AppComManager cancalHandlesForObject:self];
}
-(void)changeTheme
{
    _themeTable.backgroundView = nil;
    BanBu_ImageView *i = [[[BanBu_ImageView alloc] initWithBackGroundImageType:UIImageViewCreatTypeTable] autorelease];
    _themeTable.backgroundView = i ;
}
- (void)viewDidLoad
{
    [super viewDidLoad];
    //请从下面列表中选择您喜欢的主题
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(downloadComplete:) name:@"downLoadThemeComplete" object:nil];
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(changeTheme) name:kThemeDidChangeNotification object:nil];
    
    self.title = NSLocalizedString(@"changeTheme", nil);
//    BanBu_NavButton *btn_return=[[BanBu_NavButton alloc] initWithButtonType:UIButtonCreatTypeBack];
//    [btn_return addTarget:self action:@selector(popself) forControlEvents:UIControlEventTouchUpInside];
//    CGFloat btnLen1 = [NSLocalizedString(@"returnButton", nil) sizeWithFont:[UIFont systemFontOfSize:14] constrainedToSize:CGSizeMake(100, 30)].width;
//    btn_return.frame=CGRectMake(0, 0, btnLen1+20, 30);
//    //    [btn_return setTitleEdgeInsets:UIEdgeInsetsMake(3, 9, 2, 2)];
//    [btn_return setTitle:NSLocalizedString(@"returnButton", nil) forState:UIControlStateNormal];
//    btn_return.titleLabel.font = [UIFont systemFontOfSize:14];
//    UIBarButtonItem *bar_itemreturn=[[[UIBarButtonItem alloc] initWithCustomView:btn_return] autorelease];
//    self.navigationItem.leftBarButtonItem = bar_itemreturn;
//    [btn_return release];
    
    
    NSMutableArray *arr = [[NSMutableArray alloc] initWithArray:ThemeManager.themeExitArr];
    themeArr = arr;
    _themeTable = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, 320, __MainScreen_Height-44)];
    _themeTable.delegate = self;
    _themeTable.dataSource =  self;
    BanBu_ImageView *i = [[[BanBu_ImageView alloc] initWithBackGroundImageType:UIImageViewCreatTypeTable] autorelease];
    _themeTable.backgroundView = i ;
    [self.view addSubview:_themeTable];
    [AppComManager getBanBuData:BanBu_Get_Theme_List par:nil delegate:self];
    
    selectedImageView = [[UIImageView alloc] initWithFrame:CGRectMake(300,cellHeight-10, 72, 72)];
    selectedImageView.center = CGPointMake(160, 62);
    selectedImageView.image = [UIImage imageNamed:@"selecttheme.png"];
    
    CGSize size = [NSLocalizedString(@"selectTheme", nil) sizeWithFont:[UIFont boldSystemFontOfSize:16] constrainedToSize:CGSizeMake(300, 1000) lineBreakMode:kTextLineBreakByWordWrapping];
    
    UIView *aView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 320, size.height+80)];
    UIView *roundView = [[UIView alloc] initWithFrame:CGRectMake(5, 20, 310, 42+size.height)];
    roundView.layer.cornerRadius = 8.0;
    roundView.layer.borderWidth = 0.8;
    roundView.layer.borderColor = [[UIColor lightGrayColor] CGColor];
    roundView.backgroundColor = [UIColor clearColor];
    
    UILabel *tipLabel= [[UILabel alloc] initWithFrame:CGRectMake(0, 10, 310, 20)];
    tipLabel.backgroundColor = [UIColor clearColor];
    tipLabel.textAlignment = kTextAlignmentCenter;
    tipLabel.textColor = [UIColor blackColor];
    tipLabel.font = [UIFont boldSystemFontOfSize:16];
    tipLabel.text = NSLocalizedString(@"helpfulTitle", nil);
    [roundView addSubview:tipLabel];
    [tipLabel release];
    
    UILabel *helpLabel= [[UILabel alloc] initWithFrame:CGRectMake(0, 30, 310, size.height)];
    helpLabel.backgroundColor = [UIColor clearColor];
    helpLabel.textAlignment = kTextAlignmentCenter;
    helpLabel.numberOfLines = 2;
    helpLabel.textColor = [UIColor darkGrayColor];
    helpLabel.font = [UIFont boldSystemFontOfSize:16];
    helpLabel.text = NSLocalizedString(@"selectTheme", nil);
    [roundView addSubview:helpLabel];
    [helpLabel release];
    [self.view addSubview:roundView];
    [roundView release];
    [aView addSubview:roundView];
    _themeTable.tableHeaderView = aView;
    [aView release];
    
}
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [themeArr count]+1;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *cellIndentifier = @"themeCellIndentifier";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIndentifier];
    
    if(!cell)
    {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIndentifier]autorelease];
        cell.backgroundColor = [UIColor clearColor];
    }
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
    
    UIButton *statusBtn = (UIButton *)[cell viewWithTag:5789+indexPath.row];
    
    if(statusBtn)
    [statusBtn removeFromSuperview];
    
        UIButton *statusButton = [UIButton buttonWithType:UIButtonTypeCustom];
        statusButton.frame =  CGRectMake(240, 80, 70, 30);
        [statusButton setBackgroundImage:[UIImage imageNamed:@"themeStatus.png"] forState:UIControlStateNormal];
        
        statusButton.titleLabel.font = [UIFont systemFontOfSize:12];
        statusButton.titleLabel.textColor = [UIColor whiteColor];
        statusButton.tag = indexPath.row+5789;
    
    if(!indexPath.row)
    {
        UIImageView *img = [[UIImageView alloc] initWithFrame:CGRectMake(10, 10, 300,cellHeight-20)];
        [img setImage:[UIImage imageNamed:@"classic_blue.jpg"]];
        [cell.contentView addSubview:img];
        [img release];
        if([ThemeManager.themeName isEqual:@"default"])
        {
            [selectedImageView removeFromSuperview];
            currentThemeRow = 0;
            [cell.contentView addSubview:selectedImageView];
        }
        [statusButton setTitle:NSLocalizedString(@"haveDownload", nil) forState:UIControlStateNormal];
        [cell.contentView addSubview:statusButton];
        
    }
    else
    {
        UIImageView *img = [[UIImageView alloc] initWithFrame:CGRectMake(10, 10, 300, cellHeight-20)];
        NSString *urlString = [[themeArr objectAtIndex:indexPath.row-1] valueForKey:@"urlpic"];
        NSString *picPath  = [ThemeManager.themePicPath stringByAppendingPathComponent:[urlString substringFromIndex:urlString.length-10]];
        UIImage *image = [UIImage imageWithContentsOfFile:picPath];
        if(image)
        {
            img.image = image;
        }
        else
        {
            [TKLoadingView showTkloadingAddedTo:self.view point:CGPointMake(160,160) title:NSLocalizedString(@"loadingNotice", nil) activityAnimated:YES];
            [img setImageWithURL:[[themeArr objectAtIndex:indexPath.row-1] valueForKey:@"urlpic"] placeholderImage:[UIImage imageNamed:@"ThemeChangeDefault.png"] options:SDWebImageCacheMemoryOnly andType:0 success:^(UIImage *image) {
                [TKLoadingView dismissTkFromView:self.view animated:YES afterShow:0];
            } failure:^(NSError *error) {
                
            }];
            
            [ThemeManager downLoadThemeImageWithURL:[[themeArr objectAtIndex:indexPath.row-1] valueForKey:@"urlpic"]];
        }
        
        [cell.contentView addSubview:img];
        [img release];
        
        if([[[themeArr objectAtIndex:indexPath.row-1]valueForKey:@"urlpic"] rangeOfString:ThemeManager.themeName].location!=NSNotFound)
        {
            [selectedImageView removeFromSuperview];
            currentThemeRow = indexPath.row;
            [cell.contentView addSubview:selectedImageView];
        }
        if([ThemeManager.themeDown objectForKey:[urlString substringFromIndex:urlString.length-10]])
        {
            [statusButton setTitle:NSLocalizedString(@"haveDownload", nil) forState:UIControlStateNormal];
        }
        else if([ThemeManager.themeDownLoading objectForKey:[urlString substringFromIndex:urlString.length-10]])
        {
            [statusButton setTitle:NSLocalizedString(@"isDownloading", nil) forState:UIControlStateNormal];
            if([_themeTable viewWithTag:indexPath.row+1234])
            {
                ETActivityIndicatorView *tfInfic = (ETActivityIndicatorView *)[_themeTable viewWithTag:indexPath.row+1234];
                [tfInfic removeFromSuperview];
            }
                ETActivityIndicatorView *tfIndic = [[ETActivityIndicatorView alloc] initWithFrame:selectedImageView.frame];
                tfIndic.tag = indexPath.row+1234;
                [cell.contentView addSubview:tfIndic];
                [tfIndic startAnimating];
                [tfIndic release];
        }
        else
        {
            [statusButton setTitle:@"0.5M" forState:UIControlStateNormal];
        }
        [cell.contentView addSubview:statusButton];
    }
    return cell;
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return cellHeight;
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    selectThemeRow = indexPath.row;
    
    UIButton *statusButton = (UIButton *)[self.view viewWithTag:5789+indexPath.row];
    
    if(selectThemeRow != currentThemeRow)
    {
        NSString *urlpic = nil;
        if(indexPath.row)
        {
            urlpic = [[themeArr objectAtIndex:indexPath.row-1] valueForKey:@"urlpic"];
        }
        if(!indexPath.row)
        {
            
            UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
            [selectedImageView removeFromSuperview];
            [cell.contentView addSubview:selectedImageView];
            
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"pleaseConfirm", nil) message:NSLocalizedString(@"themeChangeTip", nil) delegate:self cancelButtonTitle:NSLocalizedString(@"cancleChange", nil) otherButtonTitles:NSLocalizedString(@"confirmChange", nil), nil];
            [alert show];
            [alert release];
            [ThemeManager setThemeName:@"default"];
        }
        //截取后主题图片url的后十位为名字
        else if([ThemeManager.themeDown objectForKey:[urlpic substringFromIndex:urlpic.length-10]])
        {
            [ThemeManager setThemeName:[urlpic substringFromIndex:urlpic.length-10]];
            UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
            [selectedImageView removeFromSuperview];
            [cell.contentView addSubview:selectedImageView];
            
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"pleaseConfirm", nil) message:NSLocalizedString(@"themeChangeTip", nil) delegate:self cancelButtonTitle:NSLocalizedString(@"cancleChange", nil) otherButtonTitles:NSLocalizedString(@"confirmChange", nil), nil];
            [alert show];
            [alert release];
        }
        
        else if(![ThemeManager.themeDownLoading objectForKey:[urlpic substringFromIndex:urlpic.length-10]])
        {
            [AppComManager downLoadFileWithUrl:[[themeArr objectAtIndex:indexPath.row-1] valueForKey:@"urlzip"] withsaveName:[NSString stringWithFormat:@"%d%@.zip",indexPath.row,[urlpic substringFromIndex:urlpic.length-10]]  delegate:MyAppDataManager];//将行数放到名字里传入,用来记录哪一行需要刷新
                [UIView animateWithDuration:0.5 animations:^{
                [statusButton setTitle:NSLocalizedString(@"isDownloading", nil) forState:UIControlStateNormal];
                statusButton.frame =  CGRectMake(230, 80, 80, 30);
            }];
            
            [ThemeManager.themeDownLoading setObject:[NSNumber numberWithBool:YES] forKey:[urlpic substringFromIndex:urlpic.length-10]];
            
            ETActivityIndicatorView *tfIndic = [[ETActivityIndicatorView alloc] initWithFrame:selectedImageView.frame];
            UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
            tfIndic.tag = indexPath.row+1234;
            [cell.contentView addSubview:tfIndic];
            [tfIndic release];
            [tfIndic startAnimating];
        }}
    
}
- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
- (void)banbuRequestDidFinished:(NSDictionary *)resDic error:(NSError *)error
{
    self.view.userInteractionEnabled = YES;
    if(error)
    {
        //        NSLog(@"主题列表获取失败");
    }
    else
    {
        if ([resDic valueForKey:@"ok"])
        {
            [themeArr removeAllObjects];
            if ([[resDic valueForKey:@"list"] isKindOfClass:[NSArray class]])
            {
                [themeArr addObjectsFromArray:[resDic valueForKey:@"list"]];
                [ThemeManager.themeExitArr removeAllObjects];
                [ThemeManager.themeExitArr addObjectsFromArray:themeArr];
                [UserDefaults setValue:ThemeManager.themeExitArr forKey:@"exitTheme"];
                [_themeTable reloadData];
            }
            
        }
    }
}
-(void)downloadComplete:(NSNotification *)notification
{
    NSDictionary *resDic = notification.userInfo;
    NSLog(@"%@",resDic);
    if(![[resDic valueForKey:@"ok"] boolValue])
    {
        ETActivityIndicatorView *tf = (ETActivityIndicatorView *)[_themeTable viewWithTag:[[resDic valueForKey:@"row"] intValue]+1234];
        [tf stopAnimating];
        [tf removeFromSuperview];
            [UIView animateWithDuration:0.5 animations:^{
            UIButton *statusButton = (UIButton *)[self.view viewWithTag:5789+[[resDic valueForKey:@"row"] intValue]];
            [statusButton setTitle:NSLocalizedString(@"newsState4", nil) forState:UIControlStateNormal];
            statusButton.frame =  CGRectMake(240, 80, 70, 30);
        }];
        return;
    }
    ETActivityIndicatorView *tf = (ETActivityIndicatorView *)[_themeTable viewWithTag:[[resDic valueForKey:@"row"] intValue]+1234];
    [tf stopAnimating];
    [tf removeFromSuperview];
        [UIView animateWithDuration:0.5 animations:^{
        UIButton *statusButton = (UIButton *)[self.view viewWithTag:5789+[[resDic valueForKey:@"row"] intValue]];
        [statusButton setTitle:NSLocalizedString(@"haveDownload", nil) forState:UIControlStateNormal];
        statusButton.frame =  CGRectMake(240, 80, 70, 30);
    }];
}
#pragma mark - UIAlertViewDelegate
-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if(buttonIndex == 1)
    {
        currentThemeRow = selectThemeRow;
        //        [self.navigationController popViewControllerAnimated:YES];
    }
    else if(buttonIndex == 0)
    {
        [selectedImageView removeFromSuperview];
        UITableViewCell *cell = [self.themeTable cellForRowAtIndexPath:[NSIndexPath indexPathForRow:currentThemeRow inSection:0]];
        if(currentThemeRow)
        {
            [ThemeManager setThemeName:[[[themeArr objectAtIndex:currentThemeRow-1] valueForKey:@"urlpic"] substringFromIndex:[[[themeArr objectAtIndex:currentThemeRow-1] valueForKey:@"urlpic"] length]-10]];
        }
        else
        {
            [ThemeManager setThemeName:@"default"];
        }
        [cell.contentView addSubview:selectedImageView];
    }
}
@end
